/*
 * AnalogInputRelay.cpp
 *
 *  Created on: 2012. 10. 22.
 *      Author: dalxx
 */
#include <Arduino.h>
#include "RelayAI.h"

namespace PLCLib {

RelayAI::RelayAI() {
	this->aiList=NULL;
	this->relayList=NULL;
	this->numRelay=0;
	this->Vref=0.0;
}

RelayAI::~RelayAI() {
	this->removeAll();
}

void PLCLib::RelayAI::calculateStatus() {
	int i;
	for(i=0;i<this->numRelay;i++)
	{
		int an=analogRead(this->aiList[i].port);

		if(an>=this->aiList[i].rangeMin && an<=this->aiList[i].rangeMax)
		{
			this->relayList[i].status=this->aiList[i].rangeType;
		}
		else this->relayList[i].status=!this->aiList[i].rangeType;
	}

}

void RelayAI::init(int num_relay, Relay* relay_list, int AIrefType, float Vref) {
	this->removeAll();
	this->numRelay=num_relay;
	this->relayList=relay_list;
	this->aiList=(AIDesc*)malloc(this->numRelay*sizeof(AIDesc));
	int type=0;
	switch(AIrefType)
	{
	case 0: // DEFAUT
		type=DEFAULT;
		break;
	case 1: // INTERNAL
		type=INTERNAL;
		break;
	case 2: // EXTERNAL
		type=EXTERNAL;
		break;
	}
	analogReference(type);
	this->Vref=Vref;
}

void RelayAI::removeAll() {
	free(this->aiList);
	this->aiList=NULL;
	this->relayList=NULL;
	this->numRelay=0;
}

void PLCLib::RelayAI::setRelay(int index, uint8_t pin,
		float rangeMin, float rangeMax, bool rangeType) {
	this->aiList[index].port=pin+A0;
	this->aiList[index].rangeMax=(1024*rangeMax)/this->Vref;
	this->aiList[index].rangeMin=(1024*rangeMin)/this->Vref;
	this->aiList[index].rangeType=rangeType;
}

} /* namespace PLCLib */
